﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Zyg.SSO.Core.Business;

namespace Zyg.SSO.Web.Admin.Account
{
    public partial class AddAccount : Zyg.SSO.Web.BasePage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!base.Account.HavePermission(Permission.AccountManage))
            {
                throw new Exception("你无权查看此页面");
            }
        }

        /// <summary>
        /// Submit
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void BtnSubmit_Click(object sender, EventArgs e)
        {
            Zyg.SSO.Core.Business.SysSetting setting = Zyg.SSO.Core.Business.SysSetting.GetCurrent();
            Zyg.SSO.Core.Business.Account account = new Zyg.SSO.Core.Business.Account();
            Zyg.Security.SecurityHelper sh = new Zyg.Security.SecurityHelper();

            account.Id = Guid.NewGuid();
            account.Email = AccountEmail.Text;
            account.IsAdmin = false;
            account.Name = AccountName.Text;
            account.Password = sh.ComputeMD5Hash(AccountPwd.Text);
            account.RoleID = Zyg.SSO.Core.Business.Role.User.Id;
            account.Telephone = AccountTel.Text;
            account.Remark = AccountRemark.Text;

            if (setting.RegisterCheck)
            {
                account.State = AccountState.Register;
            }
            else
            {
                account.State = AccountState.Active;
            }

            if (FileAccountPic.HasFile)
            {
                string accountContentPath = Server.MapPath("~/Content/Account/");
                string extension = Zyg.Utility.Helper.FileHelper.GetFileExtension(FileAccountPic.FileName);

                string fileName = account.Id.ToString() + extension;

                account.PictureAddress = "~/Content/Account/" + fileName;

                FileAccountPic.SaveAs(accountContentPath + fileName);
            }

            account.Save();

            Zyg.SSO.Core.Business.Log log = new Zyg.SSO.Core.Business.Log();
            log.AccountId = base.Account.Id;
            log.ModuleId = Zyg.SSO.Core.Business.Module.Account.Id;
            log.Message = string.Format("管理员 {0} 添加了用户 {1}", base.Account.Email, account.Email);

            log.Save();

            WriteBackScript("alert('添加用户成功');window.location.href='AccountList.aspx';");
        }
    }
}
